<template>
  <el-cascader
    popper-class="cascader-hide-radio-new"
    ref="areaRef"
    v-model="area"
    :props="treeProps"
    placeholder="请选择"
    :disabled="disabled"
    :style="{ width: width }"
    :clearable="clearable"
    @change="changeSelect"
  />
</template>

<script setup>
import { useUserStore } from '@/pinia/modules/user'
import { get_area_list_by_parentcode } from '@/api/system'
// import areaCode from '@/components/pub-area/areaCode.js'
import { useVModel } from '@vueuse/core'
import { computedAsync } from '@vueuse/core'
import { isNil } from 'lodash-es'

const props = defineProps({
  formValue: {
    type: Object,
    default: () => {
      return {
        longitude: '',
        latitude: '',
        locationAddress: ''
      }
    }
  },
  needValidate: {
    type: Boolean,
    default: true
  },
  prop: {
    type: String,
    default: ''
  },
  areaString: {
    type: String
  },
  clearable: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: Array,
    default(val) {
      return []
    }
  },
  width: {
    type: String,
    default: '500px'
  },
  maxLevel: {
    type: Number,
    default: 0
  },
  // 用来控制前面几层不能选择 0.省份disabled 1.市disabled 2....
  // 如果设置了disabledLevel 必须传正确的defaultArea进来
  disabledLevel: {
    type: [Number, String],
    default: 0
  },
  // 父子强制关联 true:可选任意一级  false:只能选中最后一级
  strictly: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  /*
   * search 搜索时候使用的 返回的最后一级地区code
   * registerAddress 选择户籍地址时使用
   * normalAddress  选择常住地址时使用
   */
  useType: {
    type: String,
    default: 'search'
  },
  // 区划字段类型 匹配接口需要的五级区划字段名称 详看areaName变量
  areaType:{
    type: [String,Number],
    default: 0
  }
})
const area = ref([])
const emit = defineEmits(['update:formValue'])
const comValue = useVModel(props, 'formValue', emit)
const areaRef = ref(null)
const labelString = ref()
const getData = () => {
  if (
    areaRef.value.getCheckedNodes()[0]?.pathLabels.join('') &&
    areaRef.value.getCheckedNodes()[0]?.pathLabels.join('').length > 10
  ) {
    labelString.value = areaRef.value.getCheckedNodes()[0].pathLabels.join('')
  }
}


const areaName = [
{
  index:0,
  codeArr:['provinceCode','cityCode','countyCode','streetCode','communityCode'],
  nameArr:['provinceName','cityName','countyName','streetName','communityName'],
},
{
  index:1,
  codeArr:['registerProvinceCode','registerCityCode','registerCountyCode','registerStreetCode','registerCommunityCode'],
  nameArr:['registerProvinceName','registerCityName','registerCountyName','registerStreetName','registerCommunityName'],
}
]

watch(
  () => props.formValue,
  (newValue, oldValue) => {
    let arr = []
    newValue[areaName[props.areaType].codeArr[0]] && arr.push(newValue[areaName[props.areaType].codeArr[0]])
    newValue[areaName[props.areaType].codeArr[1]] && arr.push(newValue[areaName[props.areaType].codeArr[1]])
    newValue[areaName[props.areaType].codeArr[2]] && arr.push(newValue[areaName[props.areaType].codeArr[2]])
    newValue[areaName[props.areaType].codeArr[3]] && arr.push(newValue[areaName[props.areaType].codeArr[3]])
    newValue[areaName[props.areaType].codeArr[4]] && arr.push(newValue[areaName[props.areaType].codeArr[4]])
    area.value = arr
    console.log('area.value',area.value)
  },
  { deep: true, immediate: true }
)
const treeProps = computed(() => {
  if (areaRef.value) {
    return {
      lazy: true,
      label: 'name',
      checkStrictly: true,
      lazyLoad: async (node, resolve) => {
        // console.log('初始化开始lazyLoad', area.value)
        // console.log('初始化开始props', props.disabledLevel)
        const { data, level } = node
        if (data && data.children && data.children.length !== 0) {
          return resolve([])
        }
        if (level === 0) {
          // 获取全部省份
          const r = await getArea('000000')
          const targetData = []
          for (const item of r.data) {
            const temp = {
              id: item.id,
              name: item.name,
              value: item.id,
              disabled: calDiasbled(level),
              leaf: calLeaf(item, level)
            }
            if (props.disabledLevel > -1) {
              //   item.id == areaCode.defaultProvince && targetData.push(temp)
              item.id == area.value[level] && targetData.push(temp)
            } else {
              targetData.push(temp)
            }
          }
          resolve(targetData)
        } else {
          // 根据省ID获取市

          const r = await getArea(data.id)
          const targetData = []
          for (const item of r.data) {
            const temp = {
              id: item.id,
              name: item.name,
              value: item.id,
              disabled: calDiasbled(level),
              leaf: calLeaf(item, level),
              loading: false
            }
            if (props.disabledLevel) {
              // 如果设置了不可选的level  node-level
              if (level > props.disabledLevel) {
                targetData.push(temp)
              } else {
                // console.log(area.value)
                // eslint-disable-next-line eqeqeq
                item.id == area.value[level] && targetData.push(temp)
              }
            } else {
              targetData.push(temp)
            }
          }
          const pathLabels = areaRef.value.getCheckedNodes()[0]
          resolve(targetData)
        }
        if (props.modelValue && props.modelValue.length > 0) {
      if (
        areaRef.value.getCheckedNodes()[0]?.pathLabels.join('') &&
        areaRef.value.getCheckedNodes()[0]?.pathLabels.join('').length > 10
      ) {
        labelString.value = areaRef.value
          .getCheckedNodes()[0]
          ?.pathLabels.join('')
      }
    }
      }
    }
  }else{
    return {}
  }
})

const calDiasbled = nodeLevel => {
  if (!props.strictly) {
    return false
  }
  // 如果是有层级选择限制的 && nodeLevel< 层级限制的level
  // if (props.disabledLevel > 0) {
  if (nodeLevel <= props.disabledLevel) {
    return true
  } else {
    return false
  }
}
const calLeaf = (item, level) => {
  if (isNil(props.maxLevel)) {
    return !item.hasChildren
  }
  return level >= props.maxLevel
}

const changeSelect = val => {
  getData()
  areaRef.value.getCheckedNodes()[0].isLeaf &&
    areaRef.value.togglePopperVisible(false)
  comValue.value[areaName[props.areaType].codeArr[0]] = area.value[0]
  comValue.value[areaName[props.areaType].codeArr[1]] = area.value[1]
  comValue.value[areaName[props.areaType].codeArr[2]] = area.value[2]
  comValue.value[areaName[props.areaType].codeArr[3]] = area.value[3]
  comValue.value[areaName[props.areaType].codeArr[4]] = area.value[4]
  const pathLabels = areaRef.value.getCheckedNodes()[0]
  comValue.value[areaName[props.areaType].nameArr[0]] = pathLabels.pathLabels[0]
  comValue.value[areaName[props.areaType].nameArr[1]] = pathLabels.pathLabels[1]
  comValue.value[areaName[props.areaType].nameArr[2]] = pathLabels.pathLabels[2]
  comValue.value[areaName[props.areaType].nameArr[3]] = pathLabels.pathLabels[3]
  comValue.value[areaName[props.areaType].nameArr[4]] = pathLabels.pathLabels[4]
}

const getArea = code => {
  return get_area_list_by_parentcode(code)
}

defineExpose({
  labelString
})
</script>
<style lang="scss" scoped></style>
